package com.xiaoke.api.controller;

import com.xiaoke.api.service.CouponService;
import com.xiaoke.api.service.OrderService;
import com.xiaoke.api.service.ShopService;
import com.xiaoke.entity.Coupon;
import com.xiaoke.entity.Order;
import com.xiaoke.entity.Shop;
import com.xiaoke.entity.User;
import com.xiaoke.entity.constant.Constant;
import com.xiaoke.shiro.SecurityService;
import com.xiaoke.util.common.AjaxMsg;
import com.xiaoke.util.common.ValidUtil;
import org.apache.commons.lang.Validate;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.*;

import javax.servlet.http.HttpServletRequest;
import java.util.Date;
import java.util.List;
import java.util.Map;

@RestController
@RequestMapping("/api/order")
public class OrderController {
    @Autowired
    private OrderService orderService;
    @Autowired
    private SecurityService securityService;
    @Autowired
    private ShopService shopService;
    @Autowired
    private CouponService couponService;


    @GetMapping("/cancel")
    public AjaxMsg cancelOrder(String orderId){
        Order order = orderService.selectByPrimaryKey(orderId);
        if(order == null)
            return new AjaxMsg(AjaxMsg.FAILURE,"订单不存在！");
        String status = order.getOrderStatus();
        if(!status.equals(Constant.ORDER_STATUS_WAIT_PAY) && !status.equals(Constant.ORDER_STATUS_WAIT_SEND))
            return new AjaxMsg(AjaxMsg.FAILURE,"订单无法取消！");
        orderService.cancelOrder(orderId);
        return new AjaxMsg();
    }

    @GetMapping("/detail")
    public AjaxMsg detail(String orderId){
        Map<String, Object> detail = orderService.findOrderDetail(orderId);
        return new AjaxMsg(detail);
    }

    @GetMapping("/list")
    public AjaxMsg list(Integer pageNum,Integer pageSize){
        User user = securityService.getCurrentUser();
        List<Map<String, Object>> list = orderService.findByUser(user.getId(),pageNum,pageSize);
        return new AjaxMsg(list);
    }

    @PostMapping("/submit")
    public AjaxMsg submit(HttpServletRequest request, @RequestParam(required = false) String couponId, String addressId){
        if( ValidUtil.isEmpty(addressId))
            return new AjaxMsg(AjaxMsg.FAILURE,"参数不能为空！");
        String appId = request.getHeader("appId");
        Shop shop = shopService.findByAppId(appId);
        User user = securityService.getCurrentUser();


        return orderService.createOrder(user.getId(),shop.getId(),addressId,couponId);

    }
}
